# -*- coding: utf-8 -*-
# @Time    : 2021/1/25 17:00
# @Author  : DuJiabao
# @Project : BaoZaiFanYiWuJianCe
# @FileName: CameraThread.py
# @Software: PyCharm
# @Desc    :
from GlobalStatement import *
import time
import cv2


class CameraThread(object):
    """
    拍照的线程
    """
    def __init__(self):
        cap = cv2.VideoCapture(0)
        if cap.isOpened():
            s = "The camera is on."
            print(s)
            put_message(s)
        else:
            s = "The camera on fail.Retrying"
            print(s)
            put_message(s)
            # 重试
            time.sleep(1)
            cap = cv2.VideoCapture(0)
            if cap.isOpened():
                s = "The camera is on."
                print(s)
                put_message(s)
            else:
                raise RuntimeError("The camera on fail.")
        self.cap = cap

    #     TODO: 修改摄像头的参数

    def callback(self):
        """
        当更新了炉头开合状态之后，相机捕获新照片，并放在队列里
        :return:
        """
        while True:
            if not update_lutou_open_state_queue.empty():
                ret, frame = self.cap.read()
                # 重拍五次，还不行，那就放弃了
                i = 0
                while not ret and i < 5:
                    i += 1
                    s = "Fail to capture photo."
                    print(s)
                    put_message(s)
                    time.sleep(0.1)  # 别把线程全占了
                    ret, frame = self.cap.read()
                assert i >= 5, "Fail to capture photo."

                # 更新照片队列
                photo_queue.put(frame)
                s = "Captured a picture"
                print(s)
                put_message(s)
            time.sleep(0.1)  # 别把线程全占了


if __name__ == "__main__":
    pass
